# -*- coding: utf-8 -*-

import inspect
import DatabaseHandlerInterface as DbHI
import os
import sys



class ModuleException(Exception):
    
    def __init__(self, *args):
        self.args = [a for a in args]
        
    def __str__(self):
        return  " ".join(self.args) 
        
        

class PluginManager:
    
    def __init__(self):
        self._plugins={}
        self._pluginPath=None
        self.importedDatabaseHandlerPlugins={}
    
    def setPluginPath(self,path):
        self._pluginPath=path
    
    def getPluginPath(self):
        return os.path.abspath(self._pluginPath)
    
    def getPlugins(self):
        return self._plugins
    
    
    def reloadPlugins(self):
        self._plugins={}   
        modules = self._loadModules()
        for module in modules.iterkeys():
            try:
                class_ = getattr(modules[module], module)
            except AttributeError:
                pass
            else:
                if inspect.isclass(class_)==True :
                    if issubclass(class_,DbHI.DatabasePluginInterface):
                        self._plugins[module]=class_

    
    
    def _loadModules(self):
        res = {}
        path = self._pluginPath
        if not os.path.exists(path):
            return res
								
        # check subfolders
        lst = os.listdir(path)
        sys.path.append(os.path.abspath(path))
        dir = []
        for d in lst:
            s = os.path.abspath(path) + os.sep + d
            if os.path.isdir(s) :
                sys.path.append(os.path.abspath(s))
                for module in os.listdir(s):
                    if module != '__init__.py' and module[-3:] == '.py':
                        res[module[:-3]]=__import__(module[:-3])
                        dir.append(s)
            else:
                    if d != '__init__.py' and d[-3:] == '.py':
                        res[d[:-3]]=__import__(d[:-3])
        return res
    
    



if __name__ == "__main__": 
      manager= PluginManager()
      manager.setPluginPath(".\Plugins")
      path=manager.getPluginPath()
      print (path)
      manager.reloadPlugins()
      plugins =manager.getPlugins()
      print plugins